package com.lineage.server.datatables;

import com.lineage.DatabaseFactory;
import com.lineage.server.utils.PerformanceTimer;
import com.lineage.server.utils.SQLUtil;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class ServerItemDropTable {
  private static final Log _log = LogFactory.getLog(ServerItemDropTable.class);
  
  private static ServerItemDropTable _instance;
  
  private static final Map<Integer, Integer> _dropList = new HashMap<>();
  
  public static ServerItemDropTable get() {
    if (_instance == null)
      _instance = new ServerItemDropTable(); 
    return _instance;
  }
  
  private ServerItemDropTable() {
    load();
  }
  
  private void load() {
    PerformanceTimer timer = new PerformanceTimer();
    Connection con = null;
    PreparedStatement pstm = null;
    ResultSet rs = null;
    try {
      con = DatabaseFactory.get().getConnection();
      pstm = con.prepareStatement("SELECT * FROM `w_限制物品丢地上`");
      rs = pstm.executeQuery();
      while (rs.next()) {
        int itemid = rs.getInt("itemid");
        if (ItemTable.get().getTemplate(itemid) == null) {
          _log.error("限制丢弃物品资料错误: 没有这个编号的道具:" + itemid);
          continue;
        } 
        int max = rs.getInt("max");
        _dropList.put(new Integer(itemid), Integer.valueOf(max));
      } 
      _log
        .info("载入限制丢弃物品物品资料数量: " + _dropList.size() + "(" + timer.get() + "ms)");
    } catch (SQLException e) {
      _log.error(e.getLocalizedMessage(), e);
    } finally {
      SQLUtil.close(rs);
      SQLUtil.close(pstm);
      SQLUtil.close(con);
    } 
  }
  
  public int getMaxCount(int itemid) {
    if (_dropList.containsKey(Integer.valueOf(itemid)))
      return ((Integer)_dropList.get(new Integer(itemid))).intValue(); 
    return -1;
  }
  
  public Integer getTemplate(int itemid) {
    return _dropList.get(new Integer(itemid));
  }
  
  public Map<Integer, Integer> getList() {
    return _dropList;
  }
  
  public int size() {
    return _dropList.size();
  }
}
